<template>
  <div>
    <el-button type="success" plain @click="dialogAddCommunity=true">新增推荐</el-button>
    <el-button type="success" plain @click="selectMeCommunity">我的发布</el-button>
    <el-button type="success" plain @click="myLikeCommunity">我的喜欢</el-button>
    <el-button type="success" plain @click="BackHome">返回主页</el-button>
    <el-dialog :title="dialogAddTitle" v-model="dialogAddCommunity" :before-close="handleClose" style="width: 30vw;height: 90vh;margin-top: 50px">
      <el-input placeholder="这一刻的想法..." v-model="addCommunityForm.content"></el-input>
      <!--  图片上传开始  -->
      <el-upload
          v-model:file-list="fileList"
          action="http://localhost:8080/yyt/file/upload"
          name="file"
          limit="9"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :with-credentials='true'
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
      <!--  图片上传结束  -->

      <!-- 选择景区-->
      <span>定位:</span>
      <el-select
          v-model="addCommunityForm.sceneId"
          clearable
          placeholder="位置"
          style="width: 240px"
      >
        <el-option
            v-for="item in scene"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
      <el-rate
          v-model="addCommunityForm.score"
          :texts="[1,2,3,4,5]"
          show-text
      />
      <span>分</span>

      <!-- @click="post" 如果post方法不传参,后面的小括号可以省略不写   -->
      <el-button type="primary" @click="post"
                 style="width: 100px;margin:10px;font-weight:bold;">发布</el-button>
    </el-dialog>
  </div>


<!--  主页面--------------------------------------------->
    <div v-for="community in communityArr" :key="community.id" style="display: inline-block;width: 25%;padding-left: 40px">
      <el-card style="width: 23vw;height: 75vh">
       <template #header>
         <div style="display: flex; align-items: center;">
           <el-dropdown trigger="click">
                <span class="avatar-wrapper">
                    <el-avatar :size="40" :src="userUrl(community)" />
                </span>
<!--             <template #dropdown>
               <el-dropdown-menu slot="dropdown">
                 <el-dropdown-item @click="">他的信息</el-dropdown-item>
                 <el-dropdown-item @click="">私聊</el-dropdown-item>
               </el-dropdown-menu>
             </template>-->
           </el-dropdown>
           <span style="padding-left: 5px">{{community.username}}</span>

           <el-rate
               v-model="community.score"
               disabled
               show-score
               text-color="#ff9900"
               score-template="{value} 分"
               style="padding-left: 70px"
           />
         </div>
       </template>
       <el-carousel height="43vh">
         <el-carousel-item v-for="url in urls(community)">
           <el-image
               :src="url"
               style="height: 100%;width: 100%"
               :zoom-rate="5"
               :initial-index="0"
               :preview-src-list="urls(community)"
               :preview-teleported=true
               :fit="cover"/>
         </el-carousel-item>
       </el-carousel>
       <el-card class="box-card" style="margin-bottom: 10px;height: 10vh">
         <span>{{community.content}}</span>
       </el-card>
         <span>定位为：{{community.name}}</span>
       <div style="float: right;padding: 10px">
         <el-tooltip
             class="box-item"
             effect="dark"
             content="展开评论"
             placement="top"
         >
           <el-button type="primary" :icon="ArrowDownBold" circle @click="dialogLoadComment(community.id)"/>
         </el-tooltip>
         <el-tooltip
             class="box-item"
             effect="dark"
             content="喜欢"
             placement="top"
         >
         <el-button v-if="community.likeStatue == false" type="primary" :icon="Star" circle @click="saveMyLikeCommunity(community.id)"/>
         <el-button v-if="community.likeStatue == true"  type="primary" :icon="StarFilled" circle @click="unlikeMyLikeCommunity(community.id)"/>
         </el-tooltip>
<!--         <el-tooltip
             class="box-item"
             effect="dark"
             content="收藏"
             placement="top"
         >
         <el-button type="primary" :icon="Star" circle />
         </el-tooltip>-->
         <el-tooltip
             class="box-item"
             effect="dark"
             content="分享"
             placement="top"
         >
         <el-button type="primary" :icon="Share" circle />
         </el-tooltip>
         <el-tooltip
             class="box-item"
             effect="dark"
             content="删除"
             placement="top"
         >
         <el-button type="primary" :icon="DeleteFilled" v-if="showDeleteButton" @click="deleteCommunity(community.id)"/>
         </el-tooltip>
         <!--      <el-button type="danger" :icon="Delete" circle />-->
       </div>
     </el-card>
      <el-dialog :title="dialogTitle" v-model="dialogComment" :before-close="handleClose" style="width: 30vw;height: 80vh;overflow-y:auto;margin-top: 50px">
        <span>评论：</span><el-input
              v-model="addCommentForm.content"
              style="width: 300px"
              maxlength="30"
              placeholder="善语结善缘，恶语伤人心"
              show-word-limit
              type="text"
          />
        <el-button type="primary" round @click="addComment()">评论</el-button>
        <el-row v-for="comment in commentArr">
          <el-col :span="6">{{comment.username}}:</el-col>
          <el-col :span="18">{{comment.content}}</el-col>
        </el-row>
        <el-row :gutter="10">
        </el-row>
      </el-dialog>
  </div>
</template>

<script setup>
import {
  //删除
  DeleteFilled,
  ArrowDownBold,
  Comment, //评论
  MagicStick,
  Star, //未选中喜欢
  StarFilled, //选中喜欢
  Share, Rank, //分享
  /*User,
  Check,
  Edit,
  Message,
  Search,
  Delete,  //删除*/
} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {onMounted, ref} from "vue";
import qs from "qs";
import axios from "axios";
import router from "@/router";

//获取当前登录用户
const user = ref(getUser());

const userUrl = (community) =>{
  let url = BASE_URL + community.imgUrl;
  return url;
}

//标签触发
const BackHome = () =>{
  // 刷新当前页面
  // 或者使用 location.reload(true) 来强制从服务器重新加载资源，而不是从缓存
  window.location.reload(true);
}

//控制新增community弹窗是否显示
const dialogAddCommunity = ref(false)
//新增community弹窗标签
const dialogAddTitle = ref('新增')
//图片上传开始
const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post(BASE_URL+'/yyt/file/remove?imgUrl='+imgUrl)
      .then((response)=>{
        if (response.data.code==2002){
          ElMessage.success('删除成功!');
        }
      })
}
const handlePictureCardPreview = (uploadFile) => {
  dialogVisible.value = true;
  dialogImageUrl.value = uploadFile.url
}
//图片上传结束

//定义变量用来保存起止时间
const times = ref([]);
const addCommunityForm = ref({
  userId:'',
  sceneId:'',
  content:'',
  score:'',
  imgUrls:''
});
const post = ()=>{
  //得到当前登录的用户信息,因为user对象只给下面的JS代码使用,所以无需定义为响应式变量
  let user = getUser();
  //如果用户信息为空,提示并跳转至登录页,注意需要使用return关键字结束post方法
  if (user == null){
    alert('请先登录!');
    router.push('/login');
    return;
  }
  //判断是否上传图片
  if (fileList.value.length > 0){//说明用户传图片了
    let imgUrls = [];//准备数组,用来存多张图片路径
    for (let file of fileList.value){//遍历响应式数组
      //依次遍历得到每个文件的响应路径
      let imgUrl = file.response.data;
      //每得到一个路径,就存入imgUrls数组中
      imgUrls.push(imgUrl);
      // /2024/05/17/2aee3eff-4f2b-42cf-bb12-db992d56378b.png,/2024/05/17/03229ac5-c83b-4a30-ac08-69dc532410d1.jpg
    }
    //循环结束,得到所有的图片路径,将路径赋值给weibo对象,一起发给后端新增微博
    addCommunityForm.value.imgUrls = imgUrls.toString();
  }
  //给微博对象设置作者id 注意:JS属性可以动态添加!
  addCommunityForm.value.userId = user.id;
  //将JS对象转为查询字符串格式
  let data = qs.stringify(addCommunityForm.value);
  //给后端发送请求
  axios.post(BASE_URL+'/yyt/community/save',data).then((response)=>{
    if (response.data.code==2000){
      ElMessage.success('添加完成!');
      //TODO 后面写完查询后,新增完毕也需要重新加载所有的申请单数据!
      loadAllCommunity();
      dialogAddCommunity.value = false;
      addCommunityForm.value = {};
      fileList.value = [];
      times.value = [];
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}

const urls = (community)=>{
  if (community.imgUrls == null){
    return null;
  }
  let urlsArr = community.imgUrls.split(',')
  for (let i = 0; i < urlsArr.length; i++) {
    urlsArr[i] = BASE_URL + urlsArr[i];
  }
  return urlsArr;
}

const fullScreenVisible = ref(false); // 控制全屏模态框的显示与隐藏
const fullScreenImageUrl = ref(''); // 全屏预览时显示的图片 URL
const showFullScreenModal = (community)=> {
    let urlsArr = urls(community);
    // 假设你想要预览第一张图片
    fullScreenImageUrl.value = urlsArr[0];
    fullScreenVisible.value = true;
}

//选择器
/*const value = ref('')
const options = [
  {
    value: '1',
    label: '北京',
  },
  {
    value: '2',
    label: '上海',
  },{
    value: '3',
    label: '杭州',
  },{
    value: '4',
    label: '成都'
  },
]*/

const value = ref('')
const scene= ref([])
const sceneArr = ref([])
const optionsArrMethod = () => {
  axios.get( BASE_URL+'/yyt/scene/select').then((response)=>{
    if (response.data.code==2000){
      sceneArr.value=response.data.data;
      scene.value = [];
      for (let i = 0; i < sceneArr.value.length; i++) {
        const item = sceneArr.value[i];
        scene.value.push({
          value: item.id, // 假设每个场景对象都有一个id属性
          label: item.name, // 假设每个场景对象都有一个name属性
        });
      }
    }else {
      ElMessage.error('失败');
    }
  })
}


//控制评论弹窗是否显示
const dialogComment = ref(false);
//定义变量控制dialog的标题
const dialogTitle = ref('详情');
const comId = ref('');
const dialogLoadComment = (communityId)=>{
  dialogComment.value = true;
  comId.value = communityId
  loadComment(communityId);
}

//实现关闭功能
const handleClose = ()=>{
  if (confirm('确认关闭本窗口?')){
    dialogComment.value=false;
    dialogAddCommunity.value=false;

  }
}

const open = () => {
  ElMessageBox.prompt('请输入你的评论：', '用户名', {
    confirmButtonText: '发送',
    cancelButtonText: '取消',
    inputPattern:
        /\b(傻)/,
    inputErrorMessage: '善语结善缘，恶语伤人心',
  })
      .then(({ value }) => {
        ElMessage({
          type: 'success',
          message: `评论成功`,
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '评论失败',
        })
      })
}


//定义数组用来装用户列表数据
const communityArr = ref([]);
//定义对象保存查询条件
const searchCommunityForm = ref({username:'',userId:'',communityId:''});
//加载所有的communities
const loadCommunity = () =>{
  searchCommunityForm.value.username = user.value.username;
  let data =qs.stringify(searchCommunityForm.value);
  return axios.get(BASE_URL+'/yyt/community/select?'+data)
}

//页面一加载立即请求加载用户数据
onMounted(()=>{
  loadAllCommunity();
  optionsArrMethod();
})
//加载所有的Community
const loadAllCommunity = () =>{
  loadCommunity().then((response)=>{
    if (response.data.code==2000){
      communityArr.value=response.data.data;
      ElMessage.info('加载成功');
    }else {
      ElMessage.error(response.data.msg)
    }
  })
}
//加载用户自己发布的
const selectMeCommunity = () =>{
  loadCommunity().then((response)=>{
    if (response.data.code==2000){
      communityArr.value=response.data.data;
      communityArr.value = communityArr.value.filter(item => item.username === user.value.username);
      showDeleteButton.value = true;
      ElMessage.info('加载成功');
    }else {
      ElMessage.error(response.data.msg)
    }
  })
}

//加载用户喜欢列表
const myLikeCommunity = () => {
  loadCommunity().then((response)=>{
    if (response.data.code==2000){
      communityArr.value=response.data.data;
      communityArr.value = communityArr.value.filter(item => item.likeStatue === true);
      // 可以在这里添加更多的逻辑代码，这些代码将在过滤操作之后执行
      ElMessage.info('加载成功');
    }else {
      ElMessage.error(response.data.msg)
    }
  })
}


const addCommentForm = ref({
  userId : "",
  communityId : "",
  content : ""
})
const addComment = () =>{
  addCommentForm.value.userId = user.value.id;
  addCommentForm.value.communityId =  comId.value;
  let data = qs.stringify(addCommentForm.value);
  axios.post(BASE_URL+'/yyt/comment/saveComment',data)
      .then((response)=>{
        if (response.data.code == 2000){
          commentArr.value = response.data.data;
          ElMessage.success('评论成功');
          addCommentForm.value.content = '';
          loadComment(comId);
        }else {
          ElMessage.error(response.data.msg);
        }
      })
}
//定义数组用来装用户列表数据
const commentArr = ref([]);
//定义对象保存查询条件
const searchCommentForm = ref({});
//加载所有的communities
const loadComment = (communityId) =>{
    searchCommentForm.value.communityId = communityId;
    let data =qs.stringify(searchCommentForm.value)
    axios.get(BASE_URL+'/yyt/comment/selectComment?'+data)
        .then((response)=>{
          if (response.data.code==2000){
            commentArr.value=response.data.data;
            ElMessage.info('加载成功');
          }else {
            ElMessage.error(response.data.msg);
          }
        })
}

//删除按钮是否显示
const showDeleteButton = ref(false);

const deleteCommunity = (id) => {
  if (confirm('您确认要删除该动态吗?')){
    axios.post(BASE_URL+'/yyt/community/delete/'+id).then((response)=>{
      if (response.data.code ==2000){
        ElMessage.success('删除成功!');
        selectMeCommunity();
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }
}

//点赞保存
//点赞状态
const saveMyLikeCommunity = (communityId) =>{
  addCommunityForm.value.userId = user.value.id;
  addCommunityForm.value.communityId =  communityId;
  let data = qs.stringify(addCommunityForm.value);
  axios.post(BASE_URL+'/yyt/community/saveMyLikeCommunity',data)
      .then((response)=>{
        if (response.data.code == 2000){
          ElMessage.success('点赞成功');
          loadAllCommunity();
        }else {
          ElMessage.error(response.data.msg);
        }
      })
}
const unlikeMyLikeCommunity = (communityId) => {
  addCommunityForm.value.userId = user.value.id;
  addCommunityForm.value.communityId = communityId;
  let data = qs.stringify(addCommunityForm.value);
  axios.post(BASE_URL+'/yyt/community/delMyLikeCommunity',data)
      .then((response)=>{
        if (response.data.code == 2000){
          ElMessage.success('取消成功');
        }else {
          ElMessage.error(response.data.msg);
        }
      })
}
</script>

<style scoped>

</style>